package cn.lww.itrip.trade.controller;

import cn.lww.itrip.trade.config.MD5;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import org.springframework.mail.MailMessage;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.util.Date;
import java.util.HashMap;
import java.util.regex.Pattern;

@Controller
public class tradeController {
             @Resource
        private MailSender mailSender;

            @Resource
        private SimpleMailMessage mailMessage;


            //手机注册
            @RequestMapping("/registerbyphone")
            public @ResponseBody
            String registerByPhone(String phone){
                if(!this.validPhone(phone)){
                    return   "false!";
                }
                 int  code  = MD5.getRandomCode();
                CCPRestSmsSDK  sdk=new  CCPRestSmsSDK();
                sdk.init("app.cloopen.com","8883");
                sdk.setAppId("8a216da87d55f9cc017d6fb470f505d8");
                sdk.setAccount("8a216da87d55f9cc017d6fb46fdc05d2","a5accdb987144320a5858898071fcd44");
            HashMap<String, Object> stringObjectHashMap = sdk.sendTemplateSMS(phone, "1", new String[]{String.valueOf(code), "1"});
            if("000000".equals(stringObjectHashMap.get("statusCode"))){
                System.out.println("发送短信成功");
            }
            return  "true";
            }
            //邮箱注册
            @RequestMapping("/registerbyemail")
            public @ResponseBody
            String registerByEmail(String email){
                    if(!this.validEmail(email)){
                            return  "false";
                    }
              String md5 = MD5.getMd5(new Date().toString(), 32);
              mailMessage.setText("你的激活码"+md5);
              mailMessage.setTo(email);
                mailSender.send(mailMessage);

                return "true";
            }




    /**			 *
     * 合法E-mail地址：
     * 1. 必须包含一个并且只有一个符号“@”
     * 2. 第一个字符不得是“@”或者“.”
     * 3. 不允许出现“@.”或者.@
     * 4. 结尾不得是字符“@”或者“.”
     * 5. 允许“@”前的字符中出现“＋”
     * 6. 不允许“＋”在最前面，或者“＋@”
     */
    private boolean validEmail(String email){
        String regex="^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
        return Pattern.compile(regex).matcher(email).find();
    }
    /**
     * 验证是否合法的手机号
     * @param phone
     * @return
     */
    private boolean validPhone(String phone) {
        String regex="^1[35789]{1}\\d{9}$";
        return Pattern.compile(regex).matcher(phone).find();
    }

}
